package com.koron.css2.serviceManage.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.koron.css2.ServerInterface;
import com.koron.css2.serviceManage.bean.AdminAreaBean;
import com.koron.css2.serviceManage.bean.AdminAreaListBean;
import com.koron.css2.serviceManage.bean.RequestBean;
import com.koron.css2.serviceManage.bean.UserInfoBean;
import com.koron.css2.serviceManage.mapper.PubAdminAreaMapper;
import com.koron.util.Constant;
import com.koron.util.JsonUtils;
import com.koron.util.secret.SecretReqUtil;
import org.apache.commons.lang3.StringUtils;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.koron.ebs.mybatis.SessionFactory;
import org.swan.bean.MessageBean;

import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 水表型号-添加
 *
 * @author 甄玉晴
 */
public class AdminAreaAdd implements ServerInterface {

    private static Logger logger = LogManager.getLogger(AdminAreaAdd.class);

    @Override
    public MessageBean<?> exec(SessionFactory factory, UserInfoBean userInfo, RequestBean req) {
        try {
        	 PubAdminAreaMapper mapper = factory.getMapper(PubAdminAreaMapper.class);
            AdminAreaBean bean = JsonUtils.objectToPojo(req.getData(), AdminAreaBean.class);
           bean.setIsLeaf(1);
           //bean.setStatus(1);
           bean.setAreaNo(getSonAreaNo(factory,bean.getAreaNo()));
           //生成fullName
           bean.setFullName(nameById(factory, bean.getParentId(),bean.getAreaName()));
           //查询父节点是否为叶子节点，如果是，更新为0
           String isLeaf = mapper.isLeaf(bean.getParentId());
           AdminAreaBean query = new AdminAreaBean();
           query.setFullName(bean.getFullName());
           List<AdminAreaListBean> list = mapper.queryListByName(query);
           if(CollectionUtil.isNotEmpty(list)) {
        	  return MessageBean.create(Constant.ILLEGAL_PARAMETER, "结构地址添加失败：该地址已存在", void.class);
           }
           if(isLeaf!=null && isLeaf.equals("1")){
        	   AdminAreaBean parent=new AdminAreaBean();
               //更新主数据库
               Map<String,Object> updateMap = new HashMap<>();
               Map<String,Object> updateSendParam = new HashMap<>();
               updateSendParam.put("ID",bean.getParentId());
               updateSendParam.put("ISLEAF",0);
               updateMap.put("tableName","pub_admin_area");
               updateMap.put("params",updateSendParam);
               updateMap.put("primaryKey","ID");
               //MessageBean<?> mobileCustomer = getMobileCustomer(StaticInfo.midMobileCustomer+"/masterData/update", updateMap);
               //if (mobileCustomer.getCode() == Constant.MESSAGE_INT_FAIL){
                   //return mobileCustomer;
               //}
               //更新本地数据库
               mapper.updateIsLeaf(updateSendParam);
           }
            bean.setCreateInfo(userInfo);
            mapper.insert(bean);
        } catch (Exception e) {
            logger.error("结构地址添加失败", e);
            return MessageBean.create(Constant.ILLEGAL_PARAMETER, "结构地址添加失败", void.class);
        }
        return MessageBean.create(Constant.MESSAGE_INT_SUCCESS, "success", void.class);
    }
    private String getSonAreaNo(SessionFactory factory,String areaNo){
        PubAdminAreaMapper mapper = factory.getMapper(PubAdminAreaMapper.class);
        String maxAreaNo = mapper.getMaxAreaNo(areaNo,areaNo.length() + 5);
        if (maxAreaNo != null){
            int i = Integer.parseInt(maxAreaNo.substring(maxAreaNo.length() - 5)) + 1;
             String tmp = String.format("%05d",i);
            return areaNo + tmp;
        }else {
            return areaNo+"00001";
        }
    }
    private String nameById(SessionFactory factory,String parentId,String sname){
        PubAdminAreaMapper mapper = factory.getMapper(PubAdminAreaMapper.class);
        StringBuilder strName = new StringBuilder();
        String pName = mapper.getNameById(parentId);
        if(!StringUtils.isEmpty(pName)){
            strName.append(pName +sname);
        }else {
            strName.append(sname);
        }
        return strName.toString();
    }
    private MessageBean<?> getMobileCustomer(String url, Object data){
    	com.koron.util.secret.RequestBean reqBean = new com.koron.util.secret.RequestBean();
        reqBean.setUrl(url);
        reqBean.setData(data);
        String result = null;
        try {
            result = SecretReqUtil.sendToGatWay(reqBean);
        }catch (Exception e){
            logger.error("调用中台移动客服失败",e);
            return MessageBean.create(Constant.MESSAGE_INT_FAIL,e.getMessage(),void.class);
        }
        MessageBean<String> info = MessageBean.create(Constant.MESSAGE_INT_SUCCESS,"操作成功",String.class);
        info.setData(result);
        return info;
    }
}